/**
 * @name: Login
 * @Description:
 * @Author: 方琦
 * @Date: 2022/8/17 8:59
 **/
import React, {useEffect} from 'react';
import {LockOutlined, UserOutlined} from '@ant-design/icons';
import {inject, observer} from "mobx-react";
import {Button, Form, Input, message} from 'antd';
import {useNavigate} from 'react-router-dom'
import login from "../assets/css/login/login.module.css"
import avatar from "../assets/images/avatar/avatar.png"

function Login(props) {
    const navigate = useNavigate();
    let loginTimer;
    const onFinish = (userInput) => {
        //为登录表单验证添加防抖
        clearTimeout(loginTimer);
        loginTimer = setTimeout(() => {
            //发起登录请求
            props.userStore.userLogin(userInput).then(data => {
                if (data.code === 200) {
                    message.success(data.msg);
                    navigate("/home");
                } else {
                    message.error(data.msg);
                }
            }).catch(err => {
                console.log(err);
                message.warning("登录出错啦，请稍后再试");
            })
        }, 1000)

    };
    useEffect(() => {
        return () => {
            clearTimeout(loginTimer);
        }
    })
    return (
        <div className={login.loginContainer}>
            <div>
                <img src={avatar} alt="用户头像"/>
            </div>
            <span className={login.title}>用户登录</span>
            <Form
                name="normal_login"
                className="login-form"
                initialValues={{
                    remember: true,
                }}
                onFinish={onFinish}
            >
                <Form.Item
                    name="account"
                    rules={[
                        {
                            required: true,
                            message: '请输入用户名',
                        },
                    ]}
                >
                    <Input prefix={<UserOutlined className="site-form-item-icon"/>} placeholder="用户名"/>
                </Form.Item>
                <Form.Item
                    name="password"
                    rules={[
                        {
                            required: true,
                            message: '请输入密码',
                        },
                    ]}
                >
                    <Input
                        prefix={<LockOutlined className="site-form-item-icon"/>}
                        type="password"
                        placeholder="密码"
                    />
                </Form.Item>

                <Form.Item>
                    <Button type="primary" htmlType="submit" className="login-form-button">
                        登录
                    </Button>
                </Form.Item>
            </Form>
        </div>
    );
}

export default inject("userStore")(observer(Login))
